import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, FlatList, Image, StyleSheet, RefreshControl, Alert, TouchableOpacity } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useNavigation } from '@react-navigation/native';
import Icon from 'react-native-vector-icons/FontAwesome';

const History = () => {
    const [history, setHistory] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const navigation = useNavigation();

    const fetchHistory = useCallback(async () => {
        try {
            const token = await AsyncStorage.getItem('authToken');
            const response = await fetch('http://124.222.104.145:8003/book/chapter-histories/', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json',
                },
            });
            const data = await response.json();
            if (response.ok) {
                setHistory(data.results || []);
            } else {
                Alert.alert('错误', data.detail || '获取历史失败');
            }
        } catch (error) {
            Alert.alert('错误', '网络请求失败');
        }
    }, []);

    useEffect(() => {
        fetchHistory();
    }, [fetchHistory]);

    const onRefresh = async () => {
        setRefreshing(true);
        await fetchHistory();
        setRefreshing(false);
    };

    const renderItem = ({ item }) => (
        <TouchableOpacity
            onPress={() => navigation.navigate('BookReading', {
                bookId: item.book.id,
                chapterId: item.chapter.id
            })}
            activeOpacity={0.7}
        >
            <View style={styles.item}>
                <Image source={{ uri: item.book.image }} style={styles.bookImage} />
                <View style={styles.info}>
                    <Text style={styles.bookTitle}>{item.book.title}</Text>
                    <Text style={styles.chapterTitle}>{item.chapter.title}</Text>
                    <Text style={styles.visitTime}>阅读时间: {item.visit_time}</Text>
                </View>
            </View>
        </TouchableOpacity>
    );

    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <TouchableOpacity onPress={() => navigation.goBack()}>
                    <Icon name="angle-left" size={28} color="#333" />
                </TouchableOpacity>
                <Text style={styles.headerTitle}>阅读历史</Text>
                <View style={{ width: 28 }} />
            </View>
            <FlatList
                data={history}
                keyExtractor={item => item.id.toString()}
                renderItem={renderItem}
                refreshControl={
                    <RefreshControl refreshing={refreshing} onRefresh={onRefresh} colors={['#4CAF50']} />
                }
                ListEmptyComponent={<Text style={styles.empty}>暂无历史记录</Text>}
            />
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        paddingTop: 20,
    },
    header: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 15,
        paddingTop: 40,
        paddingBottom: 10,
        backgroundColor: '#fff',
        borderBottomWidth: 1,
        borderBottomColor: '#eee',
        justifyContent: 'space-between',
    },
    headerTitle: { fontSize: 20, fontWeight: 'bold', color: '#333' },
    item: {
        flexDirection: 'row',
        backgroundColor: '#f8f8f8',
        marginHorizontal: 16,
        marginBottom: 12,
        borderRadius: 8,
        padding: 12,
        alignItems: 'center',
        elevation: 1,
    },
    bookImage: {
        width: 60,
        height: 80,
        borderRadius: 4,
        marginRight: 12,
        backgroundColor: '#eee',
    },
    info: {
        flex: 1,
    },
    bookTitle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#222',
        marginBottom: 4,
    },
    chapterTitle: {
        fontSize: 14,
        color: '#666',
        marginBottom: 4,
    },
    visitTime: {
        fontSize: 12,
        color: '#999',
    },
    empty: {
        textAlign: 'center',
        color: '#aaa',
        marginTop: 40,
        fontSize: 16,
    },
});

export default History; 